/**
 * 主布局组件
 * 包含侧边栏、顶部导航、内容区和页脚
 * 简化版本 - 适合毕业设计演示
 */
import React, { useState, useEffect } from 'react';  
import { Layout, Spin, App, Result } from 'antd';                      
import { useLocation, useNavigate } from 'react-router-dom';      
import { useSelector } from 'react-redux';                   
import SideMenu from '../components/sandbox/SideMenu';                    
import TopHeader from '../components/sandbox/TopHeader';                  
import NProgress from 'nprogress';                                        
import 'nprogress/nprogress.css';                                         
import './MainLayout.scss';                                               
import { selectCollapsed } from '../store/features/collapsedSlice';

// 导入所有可能需要的页面组件
import Home from '../views/sandbox/home/Home';
import UserList from '../views/sandbox/user-manage/UserList';
import RoleList from '../views/sandbox/right-manage/RoleList';
import RightList from '../views/sandbox/right-manage/RightList';
import NewsAdd from '../views/sandbox/news-manage/NewsAdd';
import NewsDraft from '../views/sandbox/news-manage/NewsDraft';
import NewsCategory from '../views/sandbox/news-manage/NewsCategory';
import Audit from '../views/sandbox/audit-manage/Audit';
import AuditList from '../views/sandbox/audit-manage/AuditList';
import Unpublished from '../views/sandbox/publish-manage/Unpublished';
import Published from '../views/sandbox/publish-manage/Published';
import Sunset from '../views/sandbox/publish-manage/Sunset';
import UserProfile from '../views/sandbox/user-profile/UserProfile';
import Settings from '../views/sandbox/system-settings/Settings';

// 从Layout组件中解构需要的子组件
const { Content, Footer } = Layout;

/**
 * 主布局组件 - 简化版
 */
const MainLayout: React.FC = () => {
  // 路由相关Hook
  const location = useLocation();             
  const navigate = useNavigate();
  const { message } = App.useApp(); // 使用App上下文
  
  // Redux相关Hook - 使用选择器
  const isCollapsed = useSelector(selectCollapsed);
  
  // 组件内状态
  const [loading] = useState(false);
  
  // 检查登录状态
  useEffect(() => {
    // 检查登录状态的简化版本
    const checkLogin = () => {
      const token = localStorage.getItem('token');
      if (!token) {
        message.error('登录已过期，请重新登录');
        navigate('/login', { 
          replace: true,
          state: { from: location } // 保存当前位置，以便登录后返回
        });
        return;
      }

      // 删除重定向逻辑，允许直接访问/home路径
      console.log('主布局访问路径:', location.pathname);
    };
    
    checkLogin();
    
    // 监听路径变化，重新检查登录状态
    return () => {
      // 在组件卸载时执行清理工作
    };
  }, [navigate, location.pathname, message]);
  
  // 处理路由变化的进度条
  useEffect(() => {
    NProgress.start();
    
    // 路由加载完成后结束进度条
    const timer = setTimeout(() => {
      NProgress.done();
    }, 300);
    
    return () => {
      clearTimeout(timer);
      NProgress.done(); // 确保在组件卸载时进度条完成
    };
  }, [location.pathname]);

  // 根据当前路径渲染对应组件
  const renderContent = () => {
    // 获取当前路径
    const path = location.pathname;
    console.log('当前路径:', path);
    
    // 直接根据路径映射组件，不依赖React Router的嵌套路由
    switch (path) {
      case '/home':
        return <Home />;
      case '/user-manage/list':
        return <UserList />;
      case '/right-manage/role/list':
        return <RoleList />;
      case '/right-manage/right/list':
        return <RightList />;
      case '/news-manage/add':
        return <NewsAdd />;
      case '/news-manage/draft':
        return <NewsDraft />;
      case '/news-manage/category':
        return <NewsCategory />;
      case '/audit-manage/audit':
        return <Audit />;
      case '/audit-manage/list':
        return <AuditList />;
      case '/publish-manage/unpublished':
        return <Unpublished />;
      case '/publish-manage/published':
        return <Published />;
      case '/publish-manage/sunset':
        return <Sunset />;
      case '/user-profile':
        return <UserProfile />;
      case '/system/settings':
        return <Settings />;
      default:
        // 如果没有匹配的路径，展示一个提示信息
        return (
          <Result
            status="404"
            title="页面未找到"
            subTitle={`路径 "${path}" 对应的组件不存在或未加载`}
            extra={
              <button onClick={() => navigate('/home')}>
                返回首页
              </button>
            }
          />
        );
    }
  };

  // 显示加载状态
  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        flexDirection: 'column',
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh' 
      }}>
        <Spin size="large" />
        <div style={{ marginTop: 16 }}>加载中...</div>
      </div>
    );
  }
  
  return (
    <Layout style={{ minHeight: '100vh' }}>
      {/* 侧边栏 */}
      <SideMenu />
      
      {/* 主内容区 */}
      <Layout 
        className="site-layout" 
        style={{ 
          marginLeft: isCollapsed ? 80 : 200, 
          transition: 'margin-left 0.2s'
        }}
      >
        {/* 顶部导航 */}
        <TopHeader />
        
        {/* 内容区 */}
        <Content className="site-content">
          {/* 页面内容 - 使用自定义渲染，不依赖Outlet */}
            <div className="content-container">
              {renderContent()}
            </div>
        </Content>
        
        {/* 页脚 */}
        <Footer style={{ textAlign: 'center', padding: '12px' }}>
          新闻发布管理系统 ©{new Date().getFullYear()} （高勇）
        </Footer>
      </Layout>
    </Layout>
  );
};

export default MainLayout;
